#!/bin/bash
#target: install postgresql
#version： 1.2 add service config
set -u -e
file_path="/root/postgresql-16.3.tar.gz"
install_path="/usr/local/postgresql"
data_path="/data/postgresql"
#postgres_passwd="123456"



tar_name="${file_path##*/}"
dir_name="${tar_name/.tar.gz/}"
pg_path="${install_path}/${dir_name}"
true_data_path="${data_path}/${dir_name}"

echo "开始安装编译所需依赖包..."
if ! apt update &> /dev/null;then
	echo "apt源更新失败。"
	exit
fi

if ! apt install -y  gcc make libreadline-dev zlib1g-dev pkg-config libicu-dev &> /dev/null;then
	echo "依赖安装失败"
else
	echo "依赖安装成功"
fi

tar -xvf "${file_path}" -C /usr/src/ &> /dev/null

# make bin file

if [ ! -d ${install_path} ];then
	mkdir -pv ${install_path}
fi

if [ -e "${pg_path}/bin/pg_ctl" ];then
	echo "已存在编译后的文件，不再编译${dir_name}"
else
	echo "正在编译${dir_name}中..."
	cd "/usr/src/${dir_name}"
	if  ! ./configure --prefix="${pg_path}"  &> /dev/null;then
		echo "编译失败"
		exit
	fi

	if  make -j 2 world &> /dev/null && make install -world  &>/dev/null;then
		echo "编译成功"
	else
		echo "编译失败"
		exit
	fi
	cd -
	echo "编译成功！"
fi

# init postgresql and env
if ! id postgre &> /dev/null;then
	useradd -u 5432 -s /sbin/nologin -M -d ${install_path}  postgres
fi



if [ ! -d "${true_data_path}" ];then
	mkdir -pv "${true_data_path}"
fi

chown -R postgres:postgres "${data_path}"

# cat > /etc/profile.d/pgsql.sh<<EOF
# export PGHOME=${pg_path}
# export PATH=\$PGHOME/bin/:\$PATH
# export PGDATA=${true_data_path}
# export PGUSER=postgres
# #export MANPATH=${pg_path}/share/man:\$MANPATH
# EOF
# source /etc/profile.d/pgsql.sh

#  init db and start postgresql


su - postgres -s /bin/bash -c "${pg_path}/bin/initdb -D ${true_data_path} &> /dev/null && echo init db sucess,the datapath is ${true_data_path} || { echo init failed;exit; }"




# init service file

cat > /etc/systemd/system/postgresql.service <<EOF
[Unit]
Description=PostgreSQL database server
After=network.target

[Service]
Type=forking

User=postgres
Group=postgres

# 设置数据库目录的环境变量
Environment=PGDATA=${true_data_path}

ExecStart=${pg_path}/bin/pg_ctl  -D \${PGDATA} -l \${PGDATA}/server.log  start
# 重载配置时使用的命令
ExecReload=${pg_path}/bin/pg_ctl -D \${PGDATA} -l \${PGDATA}/server.log reload
# 停止命令
ExecStop=${pg_path}/bin/pg_ctl -D \${PGDATA} -l \${PGDATA}/server.log stop

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload && echo  "postgresql service set success" || { echo service set failed;exit; }

systemctl start postgresql.service  && echo  "postgresql service set success" || { echo service set failed;exit; }



echo "
默认数据库是空密码，使用以下命令直接登录
${pg_path}/bin/psql -U postgres 

登录进去后，执行以下命令修改密码
ALTER USER postgres WITH ENCRYPTED PASSWORD 'yourpassword';"



